package com.example.module.flipper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;


public class FlipSwicher {
	public static final int DURATION = 700; 
	public static final float DEPTH = 0.0f;
	
	private View prevView, nextView;
	private FlipAction flipAction = FlipAction.DONE;
	private Bitmap prevBitmap;
	
	private volatile static FlipSwicher instance;
	
	public static FlipSwicher getInstance() {
		if (instance == null) {
			synchronized (FlipSwicher.class) {
				if (instance == null) 
					instance = new FlipSwicher();
			}
		}
		
		return instance;
	}
	
	public enum FlipAction {
		FLIP_FORWARD, FLIP_BACKWARD, DONE 
	}
	
	public FlipSwicher() {}
	
	public FlipSwicher(View prevView, View nextView, FlipAction flipAction) {
		this.prevView = prevView;
		this.nextView = nextView;
		this.flipAction = flipAction;
	}
	
	public void rotateView(WindowManager windowManager) {
		if (flipAction == FlipAction.FLIP_FORWARD)
			applyRotation(windowManager, 0, 90);
		else
			applyRotation(windowManager,0, -90);
		
		flipAction = FlipAction.DONE;
	}

	public void applyRotation(WindowManager windowManager, float fromDegree, float toDegree) {
		Display display = windowManager.getDefaultDisplay();
		final float centerX = display.getWidth() / 2.0f;
		final float centerY = display.getHeight() / 2.0f;
		boolean isForward = (flipAction == FlipAction.FLIP_FORWARD);
		
		final FlipAnimation animation = new FlipAnimation(fromDegree, toDegree, centerX, centerY, DEPTH, isForward);
		animation.reset();
		animation.setDuration(DURATION);
		animation.setFillAfter(true);
		animation.setInterpolator(new AccelerateInterpolator());
		animation.setAnimationListener(new DisplayNextView(isForward, prevView, nextView));
		
		prevView.setVisibility(View.VISIBLE);
		nextView.setVisibility(View.GONE);
		prevView.requestFocus();

		prevView.clearAnimation();
		prevView.startAnimation(animation);
	}
	
	public FlipAction getFlipAction() {
		return flipAction;
	}

	public void setFlipAction(FlipAction flipAction) {
		this.flipAction = flipAction;
	}

	public View getPrevView() {
		return prevView;
	}

	public void setPrevView(View prevView) {
		this.prevView = prevView;
	}

	public View getNextView() {
		return nextView;
	}

	public void setNextView(View nextView) {
		this.nextView = nextView;
	}

	public Bitmap getPrevBitmap() {
		return prevBitmap;
	}

	public void setPrevBitmap(Bitmap prevBitmap) {
		this.prevBitmap = prevBitmap;
	}

	public View createPrevView(Context context) {
		prevView = new FrameLayout(context);
		prevView.setBackgroundDrawable(new BitmapDrawable(prevBitmap));
		
		return prevView;
	}

}
